package com.wing.common.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wing.common.service.CommonService;
import com.wing.common.utils.HttpHelper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.LocalDateTimeUtils;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.*;
import com.wing.product.service.*;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 基础数据控制器
 *
 * @author Administrator
 * @date 2022/06/22
 */
@Validated
@RestController("a1commonController")
@RequestMapping("a1common/a1admin/a1common")
@RequiredArgsConstructor
public class CommonController {

   @Value("${platform.gatewayUrl}")
    private String url;

    @Autowired
    private ProductAttributeService productAttributeService;

    @Autowired
    private ProductAttributeValueService productAttributeValueService;

    @Autowired
    private ProductBrandService productBrandService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private ProductCategoryExtService productCategoryExtService;

    @Autowired
    private ProductMaterialCategoryService productMaterialCategoryService;

    @Autowired
    private ProductSpecService productSpecService;

    @Autowired
    private ProductSpecValueService productSpecValueService;

    @Autowired
    private ProductTypeService productTypeService;

    private final PlatformClient platformClient;
    private final ProductService productService;
    private final ProductDetailService productDetailService;
  @Autowired
  private CommonService commonService;
    /**
     * 同步产品类型属性
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品类型属性", notes = "同步")
    @PostMapping("/synchronizeProductAttribute")
    public JsonResult synchronizeProductAttribute() throws Exception {

        final String reqUri = url+"platform/product/admin/productAttribute/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductAttribute> list = JSONArray.parseArray(array.toJSONString(),ProductAttribute.class);
        if(list.size() > 0 ){
            productAttributeService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品类型属性值
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品类型属性值", notes = "同步")
    @PostMapping("/synchronizeProductAttributeValue")
    public JsonResult synchronizeProductAttributeValue() throws Exception {

        final String reqUri = url+"platform/product/admin/productAttributeValue/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductAttributeValue> list = JSONArray.parseArray(array.toJSONString(),ProductAttributeValue.class);
        if(list.size() > 0 ){
            productAttributeValueService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品品牌
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品品牌", notes = "同步")
    @PostMapping("/synchronizeProductBrand")
    public JsonResult synchronizeProductBrand() throws Exception {

        final String reqUri = url+"platform/product/admin/productBrand/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductBrand> list = JSONArray.parseArray(array.toJSONString(),ProductBrand.class);
        if(list.size() > 0 ){
            productBrandService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品分类
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品分类", notes = "同步")
    @PostMapping("/synchronizeProductCategory")
    public JsonResult synchronizeProductCategory() throws Exception {

        final String reqUri = url+"platform/product/admin/productCategory/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductCategory> list = JSONArray.parseArray(array.toJSONString(),ProductCategory.class);
        if(list.size() > 0 ){
            productCategoryService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品分类扩展子表
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品分类扩展子表", notes = "同步")
    @PostMapping("/synchronizeProductCategoryExt")
    public JsonResult synchronizeProductCategoryExt() throws Exception {

        final String reqUri = url+"platform/product/admin/productCategoryExt/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductCategoryExt> list = JSONArray.parseArray(array.toJSONString(),ProductCategoryExt.class);
        if(list.size() > 0 ){
            productCategoryExtService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步材料分类
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步材料分类", notes = "同步")
    @PostMapping("/synchronizeProductMaterialCategory")
    public JsonResult synchronizeProductMaterialCategory() throws Exception {

        final String reqUri = url+"platform/product/admin/productMaterialCategory/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductMaterialCategory> list = JSONArray.parseArray(array.toJSONString(),ProductMaterialCategory.class);
        if(list.size() > 0 ){
            productMaterialCategoryService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品类型规格
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品类型规格", notes = "同步")
    @PostMapping("/synchronizeProductSpec")
    public JsonResult synchronizeProductSpec() throws Exception {

        final String reqUri = url+"platform/product/admin/productSpec/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductSpec> list = JSONArray.parseArray(array.toJSONString(),ProductSpec.class);
        if(list.size() > 0 ){
            productSpecService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }

    /**
     * 同步产品类型规格值
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品类型规格值", notes = "同步")
    @PostMapping("/synchronizeProductSpecValue")
    public JsonResult synchronizeProductSpecValue() throws Exception {

        final String reqUri = url+"platform/product/admin/productSpecValue/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductSpecValue> list = JSONArray.parseArray(array.toJSONString(),ProductSpecValue.class);
        if(list.size() > 0 ){
            productSpecValueService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }


    /**
     * 同步产品类型
     * @return {@link JsonResult}
     */
    @ApiOperation(value = "同步产品类型", notes = "同步")
    @PostMapping("/synchronizeProductType")
    public JsonResult synchronizeProductType() throws Exception {

        final String reqUri = url+"platform/product/admin/productType/list?page=1&limit=1000";
        String tokenJson = HttpHelper.httpGet(reqUri);
        //String数据转JSONObject对象
        JSONObject jsonObject = JSON.parseObject(tokenJson);
        //获取data对应数据转JSONArray
        JSONArray array = jsonObject.getJSONArray("data");
        //JSONArray 转list对象数组
        List<ProductType> list = JSONArray.parseArray(array.toJSONString(),ProductType.class);
        if(list.size() > 0 ){
            productTypeService.saveOrUpdateBatch(list);
        }
        return JsonResult.success(tokenJson);
    }



    //常用产品包从平台添加产品数据时数据写入knife_enterprise库的pro_product pro_product_detail表

    @ApiOperation(value = "同步批量导入", notes = "插入")
    @PostMapping("/syncProductAndDetailBatch")
    public JsonResult addAll(@RequestBody List<List<ProductDetail>> list){//批量导入多个产品

        //先过滤数据，剔除已经导入过的数据
        for (int i=0;i<list.size();i++){
            for (int j = list.get(i).size() - 1; j >= 0; j--) {
                if (commonService.findAllDetailId().contains(list.get(i).get(j).getId())){
                    list.get(i).remove(j);
                }
            }
            if(list.get(i).size()==0){
                list.remove(i);
            }
        }
        if(list.size()==0){
            return JsonResult.success("数据已全部导入");
        }
        for (int i=0;i<list.size();i++){
            add(list.get(i));
        }
        return JsonResult.success("添加成功");
    }


    @ApiOperation(value = "同步导入常用刀具", notes = "插入")
    @PostMapping("/syncProductAndDetail")
    //单个规格和整个产品插入
    public JsonResult add(@RequestBody List<ProductDetail> list){

        for (int i=0;i<list.size();i++){
            if(commonService.existById(list.get(i).getProductId())!=null){//判断product表是否已经存在，已经存在就只在detail表插入新的细节信息
                if(productDetailService.add(list.get(i))==0){
                    return JsonResult.fail("添加失败");
                }
            }else {//不存在说明是第一次添加的产品product和detail表都新增
                Product product =new Product();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(Product.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(platformClient.queryProductFromPlatform("",list.get(i).getProductId()).getData(), product, copyOptions);
                if(!productService.save(product)||productDetailService.add(list.get(i))==0){
                    return JsonResult.fail("添加失败");
                }
            }
        }
        return JsonResult.success("添加成功");
    }
}
